package com.huangzhao.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.huangzhao.gulimall.common.to.es.SkuEsModel;
import com.huangzhao.gulimall.search.config.GulimallElasticSearchConfig;
import com.huangzhao.gulimall.search.constant.EsConstant;
import com.huangzhao.gulimall.search.service.ProductSaveService;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到es中
        //1.给es中建立索引product,建立好映射关系
        //2.es中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.stream().forEach(model -> {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String source = JSON.toJSONString(model);
            indexRequest.source(source, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        boolean failures = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架成功：{}, 返回数据: {}", collect, bulk);
        return failures;
    }
}
